<template>
  <div class="account-settings-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">账号设置</h1>
    </div>

    <!-- 设置内容 -->
    <el-card class="settings-card">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form
            ref="basicFormRef"
            v-model="basicForm"
            :rules="basicRules"
            class="settings-form"
            label-width="120px"
          >
            <el-form-item label="昵称">
              <el-input
                v-model="basicForm.nickname"
                placeholder="请输入昵称"
              />
            </el-form-item>
            
            <el-form-item label="头像">
              <div class="avatar-uploader">
                <el-avatar :size="100" class="current-avatar">
                  <img v-if="basicForm.avatar" :src="basicForm.avatar" alt="用户头像" />
                  <span v-else>{{ basicForm.nickname.charAt(0).toUpperCase() }}</span>
                </el-avatar>
                <el-upload
                  class="avatar-upload"
                  action="#"
                  :show-file-list="false"
                  :on-success="handleAvatarUpload"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-button type="primary" size="small">更换头像</el-button>
                </el-upload>
              </div>
            </el-form-item>
            
            <el-form-item label="个性签名">
              <el-input
                v-model="basicForm.bio"
                type="textarea"
                :rows="3"
                placeholder="请输入个性签名"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            ref="securityFormRef"
            class="settings-form"
            label-width="120px"
          >
            <el-form-item label="修改密码">
              <el-button type="primary" @click="openChangePasswordDialog">修改密码</el-button>
            </el-form-item>
            
            <el-form-item label="绑定手机">
              <div class="bind-info">
                <span>{{ userProfile.phone || '未绑定' }}</span>
                <el-button type="primary" size="small" @click="openBindPhoneDialog">
                  {{ userProfile.phone ? '更换' : '绑定' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="绑定邮箱">
              <div class="bind-info">
                <span>{{ userProfile.email || '未绑定' }}</span>
                <el-button type="primary" size="small" @click="openBindEmailDialog">
                  {{ userProfile.email ? '更换' : '绑定' }}
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form
            ref="notificationFormRef"
            v-model="notificationForm"
            class="settings-form"
            label-width="120px"
          >
            <el-form-item label="接收新消息通知">
              <el-switch v-model="notificationForm.messageEnabled" />
            </el-form-item>
            
            <el-form-item label="接收系统通知">
              <el-switch v-model="notificationForm.systemEnabled" />
            </el-form-item>
            
            <el-form-item label="接收活动提醒">
              <el-switch v-model="notificationForm.eventEnabled" />
            </el-form-item>
            
            <el-form-item label="接收邮件通知">
              <el-switch v-model="notificationForm.emailEnabled" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 隐私设置 -->
        <el-tab-pane label="隐私设置" name="privacy">
          <el-form
            ref="privacyFormRef"
            v-model="privacyForm"
            class="settings-form"
            label-width="120px"
          >
            <el-form-item label="公开我的在线状态">
              <el-switch v-model="privacyForm.showOnlineStatus" />
            </el-form-item>
            
            <el-form-item label="允许他人私信我">
              <el-switch v-model="privacyForm.allowPrivateMessage" />
            </el-form-item>
            
            <el-form-item label="公开我的学习记录">
              <el-switch v-model="privacyForm.showStudyRecords" />
            </el-form-item>
            
            <el-form-item label="公开我的收藏">
              <el-switch v-model="privacyForm.showCollections" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="savePrivacySettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="500px">
      <el-form
        ref="changePasswordFormRef"
        v-model="changePasswordForm"
        :rules="changePasswordRules"
        class="change-password-form"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="changePasswordForm.currentPassword" type="password" placeholder="请输入当前密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="请确认新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定手机弹窗 -->
    <el-dialog v-model="bindPhoneDialogVisible" title="绑定手机" width="500px">
      <el-form
        ref="bindPhoneFormRef"
        v-model="bindPhoneForm"
        :rules="bindPhoneRules"
        class="bind-phone-form"
        label-width="100px"
      >
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="bindPhoneForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="bindPhoneForm.code" placeholder="请输入验证码" />
          <el-button type="primary" size="small" @click="sendVerificationCode">获取验证码</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindPhoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindPhone">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定邮箱弹窗 -->
    <el-dialog v-model="bindEmailDialogVisible" title="绑定邮箱" width="500px">
      <el-form
        ref="bindEmailFormRef"
        v-model="bindEmailForm"
        :rules="bindEmailRules"
        class="bind-email-form"
        label-width="100px"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="bindEmailForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="bindEmailForm.code" placeholder="请输入验证码" />
          <el-button type="primary" size="small" @click="sendEmailVerificationCode">获取验证码</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindEmailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindEmail">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { useUserStore } from '@/store/user'
import { updateUserProfile } from '@/api/user'

// 用户store
const userStore = useUserStore()

// 响应式数据
const activeTab = ref('basic')
const loading = ref(false)

// 用户资料数据 - 从store获取
const userProfile = computed(() => userStore.user || {
  nickname: '未设置',
  avatar: '',
  phone: '',
  email: '',
  bio: ''
})

// 基本设置表单
const basicForm = ref({
  nickname: '',
  avatar: '',
  bio: ''
})

const basicRules: FormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ]
}

const basicFormRef = ref<FormInstance>()

// 安全设置相关
const changePasswordDialogVisible = ref(false)
const bindPhoneDialogVisible = ref(false)
const bindEmailDialogVisible = ref(false)

// 修改密码表单
const changePasswordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const changePasswordRules: FormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value !== changePasswordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const changePasswordFormRef = ref<FormInstance>()

// 绑定手机表单
const bindPhoneForm = ref({
  phone: '',
  code: ''
})

const bindPhoneRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'blur' }
  ]
}

const bindPhoneFormRef = ref<FormInstance>()

// 绑定邮箱表单
const bindEmailForm = ref({
  email: '',
  code: ''
})

const bindEmailRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'blur' }
  ]
}

const bindEmailFormRef = ref<FormInstance>()

// 通知设置表单
const notificationForm = ref({
  messageEnabled: true,
  systemEnabled: true,
  eventEnabled: true,
  emailEnabled: true
})

const notificationFormRef = ref<FormInstance>()

// 隐私设置表单
const privacyForm = ref({
  showOnlineStatus: true,
  allowPrivateMessage: true,
  showStudyRecords: true,
  showCollections: true
})

const privacyFormRef = ref<FormInstance>()

// 初始化表单数据
const initFormData = () => {
  // 初始化基本设置表单
  basicForm.value.nickname = userProfile.value.nickname || ''
  basicForm.value.avatar = userProfile.value.avatar || ''
  basicForm.value.bio = userProfile.value.bio || ''
}

// 保存基本设置
const saveBasicSettings = async () => {
  try {
    await basicFormRef.value?.validate()
    loading.value = true
    
    // 调用API更新用户资料
    const updateData = {
      nickname: basicForm.value.nickname,
      bio: basicForm.value.bio,
      avatar: basicForm.value.avatar
    }
    
    await updateUserProfile(updateData)
    
    // 更新store中的用户数据
    await userStore.fetchUserInfo()
    
    ElMessage.success('基本设置保存成功')
  } catch (error) {
    console.error('保存基本设置失败', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 保存通知设置
const saveNotificationSettings = () => {
  ElMessage.success('通知设置保存成功')
}

// 保存隐私设置
const savePrivacySettings = () => {
  ElMessage.success('隐私设置保存成功')
}

// 打开修改密码弹窗
const openChangePasswordDialog = () => {
  // 重置表单
  Object.keys(changePasswordForm.value).forEach(key => {
    changePasswordForm.value[key as keyof typeof changePasswordForm.value] = ''
  })
  changePasswordFormRef.value?.resetFields()
  changePasswordDialogVisible.value = true
}

// 修改密码
const changePassword = async () => {
  try {
    await changePasswordFormRef.value?.validate()
    loading.value = true
    
    // 调用API修改密码
    await userStore.updateInfo({
      password: changePasswordForm.value.newPassword
    } as any)
    
    ElMessage.success('密码修改成功')
    changePasswordDialogVisible.value = false
    
    // 重置表单
    changePasswordForm.value.currentPassword = ''
    changePasswordForm.value.newPassword = ''
    changePasswordForm.value.confirmPassword = ''
  } catch (error) {
    console.error('修改密码失败', error)
    ElMessage.error('修改密码失败，请重试')
  } finally {
    loading.value = false
  }
}

// 打开绑定手机弹窗
const openBindPhoneDialog = () => {
  // 重置表单
  Object.keys(bindPhoneForm.value).forEach(key => {
    bindPhoneForm.value[key as keyof typeof bindPhoneForm.value] = ''
  })
  bindPhoneFormRef.value?.resetFields()
  bindPhoneDialogVisible.value = true
}

// 发送手机验证码
const sendVerificationCode = () => {
  if (!bindPhoneForm.value.phone) {
    ElMessage.warning('请先输入手机号码')
    return
  }
  // 这里应该调用API发送验证码
  ElMessage.success('验证码已发送')
}

// 绑定手机
const bindPhone = async () => {
  try {
    await bindPhoneFormRef.value?.validate()
    loading.value = true
    
    // 调用API绑定手机
    await userStore.updateInfo({
      phone: bindPhoneForm.value.phone
    })
    
    ElMessage.success('手机绑定成功')
    bindPhoneDialogVisible.value = false
  } catch (error) {
    console.error('绑定手机失败', error)
    ElMessage.error('绑定手机失败，请重试')
  } finally {
    loading.value = false
  }
}

// 打开绑定邮箱弹窗
const openBindEmailDialog = () => {
  // 重置表单
  Object.keys(bindEmailForm.value).forEach(key => {
    bindEmailForm.value[key as keyof typeof bindEmailForm.value] = ''
  })
  bindEmailFormRef.value?.resetFields()
  bindEmailDialogVisible.value = true
}

// 发送邮箱验证码
const sendEmailVerificationCode = () => {
  if (!bindEmailForm.value.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }
  // 这里应该调用API发送验证码
  ElMessage.success('验证码已发送到邮箱')
}

// 绑定邮箱
const bindEmail = async () => {
  try {
    await bindEmailFormRef.value?.validate()
    loading.value = true
    
    // 调用API绑定邮箱
    await userStore.updateInfo({
      email: bindEmailForm.value.email
    })
    
    ElMessage.success('邮箱绑定成功')
    bindEmailDialogVisible.value = false
  } catch (error) {
    console.error('绑定邮箱失败', error)
    ElMessage.error('绑定邮箱失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理头像上传
const handleAvatarUpload = async (file: UploadFile) => {
  try {
    loading.value = true
    
    // 调用API上传头像
    const formData = new FormData()
    formData.append('file', file.raw as File)
    
    const response = await fetch('/api/user/avatar', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: formData
    })
    
    if (response.ok) {
      const result = await response.json()
      basicForm.value.avatar = result.avatarUrl
      ElMessage.success('头像上传成功')
    } else {
      throw new Error('上传失败')
    }
  } catch (error) {
    console.error('头像上传失败', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    loading.value = false
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file: File) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 监听用户数据变化，自动更新表单
watch(userProfile, () => {
  initFormData()
}, { deep: true })

// 组件挂载时初始化
onMounted(async () => {
  try {
    // 如果用户store中没有数据，先获取用户信息
    if (!userStore.user) {
      await userStore.fetchUserInfo()
    }
    // 初始化表单数据
    initFormData()
  } catch (error) {
    console.error('初始化用户数据失败', error)
    ElMessage.warning('加载用户数据失败，使用默认数据')
    initFormData()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 重置所有对话框的可见性状态
  changePasswordDialogVisible.value = false
  bindPhoneDialogVisible.value = false
  bindEmailDialogVisible.value = false
})
</script>

<style lang="scss" scoped>
.account-settings-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.settings-card {
  border-radius: 12px;
  overflow: hidden;
}

.settings-form {
  padding: 20px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.current-avatar {
  margin-bottom: 0;
}

.bind-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.change-password-form,
.bind-phone-form,
.bind-email-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>